package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.mapper.MenuMapper;
import com.ruoyi.system.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, SysMenu> implements MenuService {
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
        List<SysMenu> menuList = null;
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        if (null!=menu.getMenuName() && !menu.getMenuName().equals("")){
            wrapper.like(SysMenu::getMenuName,menu.getMenuName());
        }
        if (null!=menu.getVisible() && !menu.getVisible().equals("")){
            wrapper.eq(SysMenu::getVisible,menu.getVisible());
        }
        if (null!=menu.getStatus() && !menu.getStatus().equals("")) {
            wrapper.eq(SysMenu::getStatus, menu.getStatus());
        }
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            menuList = baseMapper.selectList(wrapper);
        }
        else {
            menu.getParams().put("userId", userId);
            menuList = baseMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    @Override
    public boolean checkMenuNameUnique(SysMenu menu) {
        Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        SysMenu sysMenu = baseMapper.selectOne(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getMenuName,menu.getMenuName()).eq(SysMenu::getParentId,menu.getParentId()));
        if (StringUtils.isNotNull(sysMenu) && sysMenu.getMenuId().longValue() != menuId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public SysMenu selectMenuById(Long menuId) {
        return baseMapper.selectById(menuId);
    }
}
